package com.wocai.jrt.orgadmin.project.service.impl;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.vteba.common.exception.ServiceException;
import com.vteba.service.generic.impl.MyBatisServiceImpl;
import com.vteba.tx.jdbc.mybatis.spi.BaseDao;
import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.JsonBean;
import com.wocai.jrt.orgadmin.approve.model.ApproveRoleGroup;
import com.wocai.jrt.orgadmin.approve.service.spi.ApproveRoleGroupService;
import com.wocai.jrt.orgadmin.flow.model.Flow;
import com.wocai.jrt.orgadmin.flow.model.FlowInstance;
import com.wocai.jrt.orgadmin.flow.model.FlowLog;
import com.wocai.jrt.orgadmin.flow.service.spi.FlowInstanceService;
import com.wocai.jrt.orgadmin.flow.service.spi.FlowLogService;
import com.wocai.jrt.orgadmin.flow.service.spi.FlowService;
import com.wocai.jrt.orgadmin.project.bean.ProjectReqBean;
import com.wocai.jrt.orgadmin.project.bean.ProjectResBean;
import com.wocai.jrt.orgadmin.project.dao.ProjectDao;
import com.wocai.jrt.orgadmin.project.model.Project;
import com.wocai.jrt.orgadmin.project.model.ProjectAttachment;
import com.wocai.jrt.orgadmin.project.model.ProjectBean;
import com.wocai.jrt.orgadmin.project.service.spi.ProjectAttachmentService;
import com.wocai.jrt.orgadmin.project.service.spi.ProjectService;
import com.wocai.jrt.orgadmin.utils.MyFileUtils;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 项目相关的service业务实现。
 * @author yinlei
 * @date 2016-3-17 17:23:18
 */
@Named
public class ProjectServiceImpl extends MyBatisServiceImpl<Project, ProjectBean, String> implements ProjectService {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(ProjectServiceImpl.class);
	// 添加了方法后，记得改为private
	private ProjectDao projectDao;
	
	@Inject
	private FlowInstanceService flowInstanceServiceImpl;
	
	@Inject
	private FlowService flowServiceImpl;
	@Inject
	private ProjectAttachmentService projectAttachmentServiceImpl;
	@Inject
	private FlowLogService flowLogServiceImpl;
	@Inject
	private ApproveRoleGroupService approveRoleGroupServiceImpl;
	
	@Override
	@Inject
	public void setBaseDao(BaseDao<Project, ProjectBean, String> projectDao) {
		this.baseDao = projectDao;
		this.projectDao = (ProjectDao) projectDao;
	}

	@Override
	public JsonBean saveProject(ProjectReqBean model,
			List<MultipartFile> fileList) throws ServiceException {
		JsonBean bean = new JsonBean();
		try {
			String orgId = UserUtils.getOrgId();
			String projectId = ObjectId.get().toString();
			model.setOrgId(orgId);
			model.setId(projectId);
			// 设为录入中
			model.setState(1);
			model.setCreateTime(new Date());

			// 流程插入
			Flow flow = new Flow();
			flow.setType(2);
			flow.setFlag(true);
			flow.setState(true);
			flow = flowServiceImpl.unique(flow);
			model.setFlowId(flow.getId());

			// 投资经理
			String employeeId =UserUtils.getUserId();
			model.setInvestEmployeeId(employeeId);
			LOGGER.info("getInvestmentHead params is [{}]",employeeId);
			ApproveRoleGroup arg = approveRoleGroupServiceImpl.getInvestmentHead(employeeId);
			LOGGER.info("getInvestmentHead result is [{}]",JSON.toJSONString(arg));
			if(arg == null){
				bean.setMessage("新增项目失败,当前理财师不属于投资部门.");
				bean.setCode(0);
				return bean;
			}
			// 投资部团队id
			model.setApproveRoleId(arg.getId());
			int result = projectDao.save(model);
			for (int i = 0; i < fileList.size(); i++) {
				ProjectAttachment pa = new ProjectAttachment();
				String url = MyFileUtils.uploadFile(fileList.get(i), "project");
				pa.setCreateTime(new Date());
				pa.setEmployeeId(UserUtils.getUserId());
				pa.setOrgId(UserUtils.getOrgId());
				pa.setProjectId(projectId);
				pa.setId(ObjectId.get().toString());
				pa.setType(1);
				pa.setUrl(url);
				projectAttachmentServiceImpl.save(pa);
			}
			// 流程实例添加
			FlowInstance flowInstance = new FlowInstance();
			flowInstance.setId(ObjectId.get().toString());
			flowInstance.setEventId(projectId);
			flowInstance.setFlowId(flow.getId());
			flowInstance.setNowStep(1);
			int resultFlow = flowInstanceServiceImpl.save(flowInstance);
			
			//流程日志添加
			FlowLog flowLog = new FlowLog();
			flowLog.setId(ObjectId.get().toString());
			flowLog.setCreateTime(new Date());
			flowLog.setEmployeeId(UserUtils.getUserId());
			flowLog.setEmployeeName(UserUtils.getUser().getName());
			flowLog.setStepName("项目添加");
			flowLog.setOrgId(UserUtils.getOrgId());
			flowLog.setEventId(projectId);
			int resultFlowLog = flowLogServiceImpl.save(flowLog);
			
			if (result == 1 && 1 == resultFlow && 1 == resultFlowLog) {
				bean.setMessage("success");
				bean.setCode(1);
				LOGGER.info("save record success.");
			} else {
				bean.setMessage("error");
				LOGGER.error("save record error.");
			}
		} catch (Exception e) {
			bean.setMessage("新增项目出错");
			throw new ServiceException(e.getMessage());
		}
		return bean;
	}

	@Override
	public JsonBean updateProject(ProjectReqBean model,
			List<MultipartFile> fileList) throws ServiceException {
		JsonBean json = new JsonBean();
		try {
			//流程日志添加
			FlowLog flowLog = new FlowLog();
			flowLog.setId(ObjectId.get().toString());
			flowLog.setCreateTime(new Date());
			flowLog.setEmployeeId(UserUtils.getUserId());
			flowLog.setEmployeeName(UserUtils.getUser().getName());
			flowLog.setStepName("项目修改");
			flowLog.setOrgId(UserUtils.getOrgId());
			flowLog.setEventId(model.getId());
			int resultFlowLog = flowLogServiceImpl.save(flowLog);
			
			int result = projectDao.updateById(model);
			if (result == 1) {
				Integer length = fileList.size();
				for (int i = 0; i < length; i++) {
					ProjectAttachment pa = new ProjectAttachment();
					String url;
					try {
						url = MyFileUtils.uploadFile(fileList.get(i), "project");
					} catch (IOException e) {
						LOGGER.error("上传文件失败");
						json.setCode(0);
						json.setMessage("上传文件失败");
						return json;
					}
					pa.setCreateTime(new Date());
					pa.setEmployeeId(UserUtils.getUserId());
					pa.setOrgId(UserUtils.getOrgId());
					pa.setProjectId(model.getId());
					pa.setId(ObjectId.get().toString());
					pa.setType(1);
					pa.setUrl(url);
					projectAttachmentServiceImpl.save(pa);
				}
			} else {
				json.setCode(0);
				json.setMessage("更新项目失败");
				return json;
			}
			if (1 != resultFlowLog) {
				json.setCode(0);
				json.setMessage("更新项目日志失败");
				return json;
			}
			json.setCode(1);
			json.setMessage("success");
			return json;
		} catch (ServiceException e) {
			throw new ServiceException(e.getMessage());
		}
	}
	
	@Override
	public List<ProjectResBean> getAllNoInProjectList(Project model) {
		return projectDao.getAllNoInProjectList(model);
	}

	@Override
	public List<ProjectResBean> getAllInStoreProjectList(Project model) {
		return projectDao.getAllInStoreProjectList(model);
	}

}
